package fi.profecons.csswindows.toolkit;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import fi.profecons.csswindows.Element;

public class Image extends Element {

	private String source;

	private float quality = 0.85f;
	
	private File file;

	private boolean forceReload;

	public Image() {
		super();
		addCommand("new Image('" + getId() + "');");
	}

	public BufferedImage getBuffer() {
		BufferedImage buffer = null;
		try{
			buffer = ImageIO.read(file);
		}catch (IOException ie){
		}
		return buffer;
	}
	
	public void load(File f) {
		file = f;
		BufferedImage buffer;
		try {
			if (f.exists()) {
				System.out.println("File exists");
				buffer = ImageIO.read(f);
				System.out.println("File read into buffer");
				if (buffer != null) {
					System.out.println("Buffer is not null");
					setSize(buffer.getWidth(), buffer.getHeight());
					System.out.println("Size set");
					String source = "?action=IMAGE_FETCH_BINARY&image_id=" + getId();
					setSource(source, String
							.valueOf(System.currentTimeMillis()));
					System.out.println("Source set");
				}
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}



	public Image(String source) {
		super();
		this.source = source;
		addCommand("new Image('" + getId() + "', '" + source + "');");
	}

	public void repaint() {
		setSource(this.source, String.valueOf(System.currentTimeMillis()));
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		setSource(source, null);
	}

	protected void setSource(String source, String time) {
		this.source = source;
		if (time != null) {

			if (source.contains("?")) {
				source = source + "&time=" + time;
			} else {
				source = source + "?time=" + time;
			}
		}
		addCommand("getElement('" + getId() + "').setSource('" + source + "');");
	}

	public float getQuality() {
		return quality;
	}

	public void setQuality(float quality) {
		this.quality = quality;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

}
